import { Button, Table, Form, Input, message, Popconfirm, Select } from 'antd'
import ModalBox from '../../../components/modalBox'
import { useState, useEffect  } from 'react';
import { service } from '../../../api/url.js'
import store from '../../../store/store.js'
import { useLocation } from 'react-router-dom';
import { getUrlSearch } from '../../../utils/utils.js'
import dayjs from 'dayjs';
import CryptoJS from "crypto-js";
const _state = store.getState()
const { TextArea } = Input;

function MyApp(props) {
    const location = useLocation();
    const columns = [
        {
            title: '序号',
            width: '5%',
            align: 'center',
            render: (text, record, index) => {
                return index + 1
            }
        },
        {
            title: '用户名',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
            align: 'center',
        },
        {
            title: '身份',
            dataIndex: 'identity',
            align: 'center',
            render: (text, record, index) => {
                console.log('record.project', record)
                switch (record.identity) {
                    case '1':
                        return (<>普通用户</>)
                    case '2':
                        return (<>管理员</>)
                    case '3':
                        return (<>所有者</>)
                }
                
            }
        },
        {
            title: '创建日期',
            dataIndex: 'createTime',
            key: 'createTime',
            width: '15%',
            align: 'center',
            render: (text, record, index) => {
                return(<>{record['createTime'] ? dayjs(record['createTime']).format('YYYY-MM-DD HH:mm:ss') : ''}</>)
            }
        },
        {
            title: '操作',
            width: '15%',
            align: 'center',
            render: (text, record, index) => {
                return (
                    <div>
                        <Button type="primary" style={{marginRight: '10px'}} onClick={() => {editUserRight(record)}}>编辑</Button>
                        <Popconfirm
                            title="删除该项目"
                            description="是否确定删除该该项目?"
                            onConfirm={() => confirm(record)}
                            okText="是"
                            cancelText="否"
                          >
                            <Button type="primary" danger>
                                撤销
                            </Button>
                          </Popconfirm>
                    </div>
                )
            }
        }
    ]
    const [dataSource, setDataSource] = useState([])
    const [total, setTotal] = useState(0)
    const [messageApi, contextHolder] = message.useMessage();
    const [showModal, setShowModal] = useState(false) // 授权对话框显示或隐藏
    const [userList, setUserList] = useState([]) // 搜索用户
    const [projectInfo, setProjectInfo] = useState({ // 操作过程中保存项目信息
        projectId: getUrlSearch(location.search).appid,
        formModel: ''
    })
    const success = (msg) => {
        messageApi.open({
            type: 'success',
            content: msg,
        });
    };
    const error = (msg) => {
        messageApi.open({
            type: 'error',
            content: msg,
        });
    };
    const confirm = (row) => {
      setProjectInfo({formModel: '6', projectId: row.projectId})
      delProject(row)
    };
    const [form] = Form.useForm();
    const onSave = () => {
        form.validateFields()
             .then((res) => {
                console.log('验证成功');
                const fromData = form.getFieldsValue()
                const params = {
                    projectId: projectInfo.projectId,
                    identity: fromData.identity ? fromData.identity : '1',
                    phone: fromData.phone,
                }
                setRightToUser(params)
              })
              .catch((err) => {
                console.log('验证失败');
              })
        
    }
    const onCancle = () => {
        setShowModal(false)
    }
    // 选择用户
    const onChange = (value) => {
    };
    // 搜索用户
    const onSearch = (value) => {
      console.log('search:', value);
      const params = {
          search: value
      }
      searchUser(params)
    };
    // 选择权限
    const handleChange = (value) => {
      console.log(`selected ${value}`);
    };
    // 编辑授权
    const editUserRight = (row) => {
        setProjectInfo({...projectInfo, formModel: 'edit'})
        setUserList([{label: `${row.phone}/${row.userName}`, value: row.phone}])
        setShowModal(true)
        setTimeout(() => {
            form.setFieldsValue({
                phone: row.phone,
                identity: row.identity
            })
        }, 200)
    }
    // 添加/修改项目授权信息
    const setRightToUser = (params) => {
        projectInfo.formModel === 'add' ?
        service.setRightToUser(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getProjectUser()
                onCancle()
            } else {
                error(res.data.msg)
            }
        }) :
        service.editUserRight(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getProjectUser()
                onCancle()
            } else {
                error(res.data.msg)
            }
        })
    }
    // 获取项目列表
    const getProjectUser = () => {
        const params = {
            pageNum: 1,
            pageSize: 10,
            projectId: projectInfo.projectId
        }
        service.getUserListByAppid(params).then(res => {
            if (res.data.status === 1) {
                setDataSource(res.data.data.list)
                setTotal(res.data.data.total)
                success(res.data.msg)
            } else {
                error(res.data.msg)
            }
        })
    }
    // 删除项目
    const delProject = (row) => {
        const params = {
            projectId: row.projectId,
            phone: row.phone
        }
        service.delUserRight(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getProjectUser()
            } else {
                error(res.data.msg)
            }
        })
    }
    // 搜索用户
    const searchUser = (params) => {
        service.searchUser(params).then(res => {
            if (res.data.status === 1) {
                let temp = res.data.data.list.map(item => {
                    return {
                        label: `${item.phone}/${item.userName}`,
                        value: item.phone
                    }
                })
                setUserList(filterUser(temp, dataSource))
            } else {
                setUserList([])
            }
        })
    }
    // 过滤数组
    const filterUser = (source, dest) => {
        const temp = dest.map(item => {
            return item.phone
        })
        temp.push(CryptoJS.AES.decrypt(getUrlSearch(location.search)._au, 'zhanle').toString(CryptoJS.enc.Utf8))
        return source.filter(item => {
            return temp.indexOf(item.value) === -1
        })
    }
    useEffect(() => {
        getProjectUser()
    }, [])
    useEffect(() => {
        if (showModal) {
            form.resetFields()
        }
    }, [showModal]);
    return (
        <div className="my-app">
            {contextHolder}
            <div className="table-header">
                <h3>应用授权</h3> <Button className="go-back-btn" danger onClick={() => {props.onBack()}}>返回</Button>
                <ModalBox title={projectInfo.formModel === 'add' ? '授予权限' : '编辑权限'} showModal={showModal}>
                    <Button type="dashed" onClick={() => {setShowModal(true);setProjectInfo({...projectInfo, formModel: 'add'})}}>授权</Button>
                    <div className="modal-box-body">
                        <Form
                            form={form}
                            className="app-form"
                            name="basic"
                            labelCol={{
                              span: 4,
                            }}
                            wrapperCol={{
                              span: 20,
                            }}
                            style={{
                              maxWidth: 600,
                            }}
                            initialValues={{
                              remember: true,
                            }}
                            autoComplete="off"
                          >
                            <Form.Item
                              label="用户："
                              name="phone"
                              rules={[
                                {
                                  required: true,
                                  message: '用户不能为空!',
                                }
                              ]}
                            >
                              <Select
                                  disabled={projectInfo.formModel === 'edit'}
                                  showSearch
                                  placeholder="手机号/用户名"
                                  optionFilterProp="children"
                                  onChange={onChange}
                                  onSearch={onSearch}
                                  filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                  }
                                  options={userList}
                                />
                            </Form.Item>
                            
                            <Form.Item
                              label="权限："
                              name="identity"
                            >
                              <Select
                                    defaultValue="1"
                                    style={{
                                      width: 120,
                                    }}
                                    onChange={handleChange}
                                    options={[
                                      {
                                        label: '普通用户',
                                        value: '1',
                                      },
                                      {
                                        label: '管理员',
                                        value: '2',
                                      },
                                      {
                                        label: '所有者',
                                        value: '3',
                                      }
                                    ]}
                                  />
                            </Form.Item>
                          </Form>
                    </div>
                    <div className="ctrl-btn-bar btn-bar-right">
                          <Button className="login-btn" type="primary" onClick={onSave}>
                            保存
                          </Button>
                          <Button onClick={onCancle}>
                            取消
                          </Button>
                    </div>
                </ModalBox>
            </div>
            <div className="table-container">
                <Table bordered dataSource={dataSource} columns={columns} rowKey="projectId" scroll={{y: 710}}/>
            </div>
            
        </div>
    )
}
export default MyApp